import axios from 'axios'
import { ElMessage  } from 'element-plus'
import { getToken } from '@/utils/auth';

// create an axios instance
const service = axios.create({
    baseURL: process.env.VITE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        if (getToken()) {
            config.headers['Authorization'] = 'Token ' + getToken();
        }
        config.headers['Content-Type'] = 'application/json'
        // config.headers['Vue-Router'] = router.currentRoute.path
        return config
    },
    error => {
        // do something with request error
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.status !== 0) {
            ElMessage({
                message: res.detail || 'Error',
                type: 'error',
                duration: 2 * 1000
            })

            // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
            if (res.code === 1 || res.code === 405 || res.code === 50014) {}
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res
        }
    },
    error => {
        return Promise.reject(error)
    }
)

export default service
